<template>
  <div>
    <van-nav-bar
        left-arrow
        @click-left="onClickLeft"
        title="资质管理"
    />
    <van-uploader v-model="fileList" accept="image/*" multiple :after-read="afterRead" :before-delete="beforeDelete"/>
  </div>
</template>

<script>
import {delQua, getQua, imgUploadBase64} from "@/api/operator";
import {setLocalOpenId,getLocalOpenId} from "@/utils/wxUtil";

export default {
  data() {
    return {
      params: {
        openId: getLocalOpenId()
      },
      fileList: [],
      fileList2: []
    };
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    // beforeRead(file, detail) {
    //   let fileType = ['image/jpeg', 'image/png', 'image/bmp']
    //   if (fileType.indexOf(file.type) === -1) {
    //     this.$toast('请上传 jpg、png、bmp 格式图片');
    //     return false;
    //   }
    //   return true;
    // },
    afterRead(file, detail) {
      if (file.length > 0) {
        file.map((item, index) => {
          item.status = 'uploading'
          item.message = '上传中...'
          this.doUploadImg(item)
        })
      }else{
        file.status = 'uploading'
        file.message = '上传中...'
        this.doUploadImg(file)
      }
    },
    beforeDelete(file, detail) {
      this.$dialog.confirm({
        title: '删除提示',
        message: '确认要删除该图片？',
      }).then(res => {
        let index = detail.index;
        let obj = this.fileList2[index]
        if (obj) {
          let params = {
            id: obj.id
          }
          delQua(params).then(res => {
            this.fileList.splice(index, 1)
            this.fileList2.splice(index, 1)
          }).catch(res => {
          })
        }
      })
      return false
    },
    doUploadImg(file){
      if (file.file.size > 1 * 1048576) { // 超出1M进行压缩，否则不压缩
        this.imageCompress(file.content).then((result) => {
          const params = {
            openId: this.params.openId,
            base64Str: result.split(',')[1]
          }
          imgUploadBase64(params).then(res => {
            file.status = 'done'
            file.message = ''
            let result = {
              id: res.data.id,
              url: res.data.url
            }
            this.fileList2.push(result);
          }).catch(res => {
            file.status = 'failed';
            file.message = '上传失败';
          });
        })
      } else {
        const params = {
          openId: this.params.openId,
          base64Str: file.content.split(',')[1]
        }
        imgUploadBase64(params).then(res => {
          file.status = 'done'
          file.message = ''
          let result = {
            id: res.data.id,
            url: res.data.url
          }
          this.fileList2.push(result);
        }).catch(res => {
          file.status = 'failed';
          file.message = '上传失败';
        });
      }
    },
    imageCompress(base64) { // 压缩图片
      let Img = new Image()
      let dataURL = ''
      Img.src = base64
      let p = new Promise(function (resolve, reject) {
        Img.onload = function () { // 要先确保图片完整获取到，这是个异步事件
          let canvas = document.createElement('canvas') // 创建canvas元素
          let width = Img.width // 确保canvas的尺寸和图片一样
          let height = Img.height
          // 默认将长宽设置为图片的原始长宽，这样在长宽不超过最大长度时就不需要再处理
          let ratio = width / height
          let maxLength = 1000
          let newHeight = height
          let newWidth = width
          // 在长宽超过最大长度时，按图片长宽比例等比缩小
          if (width > maxLength || height > maxLength) {
            if (width > height) {
              newWidth = maxLength
              newHeight = maxLength / ratio
            } else {
              newWidth = maxLength * ratio
              newHeight = maxLength
            }
          }
          ;
          canvas.width = newWidth
          canvas.height = newHeight
          canvas.getContext('2d').drawImage(Img, 0, 0, newWidth, newHeight) // 将图片绘制到canvas中
          dataURL = canvas.toDataURL('image/jpeg', 0.5) // 转换图片为dataURL
          resolve(dataURL)
        }
      })
      return p
    }
  },
  mounted() {
    getQua(this.params).then(res => {
      if (res.data !== undefined && res.data.length > 0) {
        res.data.map((item,index)=>{
          let obj = {
            id: item.id,
            url: item.url
          }
          this.fileList.push(obj)
          this.fileList2.push(obj)
        })
      }
    })
  }
}
</script>

<style lang="scss" scoped>
</style>
